<?php
namespace Home\Controller;

use Think\Controller;
class ActivityController extends CommonController {
	private $user_email = null;
	private $user_token = null;
    private $uid = null;
    private $api_status = 1;// api状态
    private $api_auth_status = 2;// api审核状态
    private $api_display = 1;// 是否显示
    private $api_enable = 1;// 是否可用
    private $api_auth_record_table = "dmp_service_authorization_record";// api申请授权记录表
    public static $api_goumai_title = '【 云途数据市场】API购买意向';//用户留言邮件title
    

    public function __construct(){
        parent::__construct();
        // 用户信息
        if($this->role != -1){// 游客
            $this->user_email = session('user_email');
            $this->uid = session('uid');
            $this->assign('user_email',$this->user_email);
            $this->user_token = session('user_token');
        }

        $this->assign('role',$this->role);
	}

    //所有错误跳转
    public function __call($method,$args){
        if(IS_POST){
            $this->ajaxReturn( array('status'=>404,'msg'=>'400 bad request','data'=>null));
        }else{
            $this->display();
        }
    }

    //云途数据市场-房价网活动页
    public function fangjia(){
        $this->assign('head_title',"云途数据市场-房价网");
        $this->display();
    }

    //地图数据运营活动页
    public function hotel(){
        header('Cache-Control: max-age=86400,must-revalidate');
        header('Last-Modified: ' .gmdate('D, d M Y H:i:s') . 'GMT' );
        header('Expires: ' .gmdate ('D, d M Y H:i:s', time() + '86400' ). 'GMT');
        
        $table = "elong_domestic_hotel";
        //本地文件缓存
        $filename = DATA_PATH."ditu_hotel.txt";
        $content = false;
        //读取文件缓存
        if(file_exists($filename)){
            $file_contents = json_decode(file_get_contents($filename),true);
            if($file_contents['expirse']>=time()){
                $content = $file_contents['content'];
            }
        }

        if($content===false){
            $expirse = time()+23*3600;
            $data = $total_data = $price_data = $hot_data = array();
            try{
                $pg = $this->conncetPgsql();
                //全国及前五名，各星级数据量
                $sql = $this->getTopHotelSql();
                $total_result = pg_query($pg,$sql);
                while($total_list = pg_fetch_object($total_result)){
                    array_push($total_data, (array)$total_list);
                }
                $total_data = $this->_format_echart_data_with_totalhotel($total_data);
                $total_data = json_encode($total_data);
                //价格占比
                $price_sql = $this->getPriceHotelSql();
                $price_result = pg_query($pg,$price_sql);
                while($price_list = pg_fetch_object($price_result)){
                    array_push($price_data, (array)$price_list);
                }
                $price_data = $this->_format_echart_data_with_persenthotel($price_data[0]);
                $price_data = json_encode($price_data);

                //热力图
                $price_range = 500;
                $hot_sql = 'select name,rank,longitude,latitude,city_name,price,img_url from elong_domestic_hotel where price > '.$price_range." limit 300";
                $hot_result = pg_query($pg,$hot_sql);
                while($hot_list = pg_fetch_object($hot_result)){
                    array_push($hot_data, (array)$hot_list);
                }
                $hot_data = $this->_format_echart_data_with_hothotel($hot_data);
                $hot_data = json_encode($hot_data);

                pg_close($pg_connect);

                $content = array('total'=>$total_data,'price'=>$price_data,'hot'=>$hot_data);
                //timp($content);die;

                $content_string = json_encode ( array('expirse'=>$expirse,'content'=>$content) );
                file_put_contents($filename, $content_string);
            }catch(exception $e){

            }   
        }
        
        $this->assign('data',$content);
        $this->display();
    }

    //酒店总量echart数据格式化
    private function _format_echart_data_with_totalhotel($data){
        if(empty($data)) return null;
        $category = $level_one = $level_two = $level_three = array();
        foreach ($data as $key=>$val){
            array_push($category,$val['city']);
            array_push($level_one,$val['one_num']);
            array_push($level_two,$val['two_num']);
            array_push($level_three,$val['three_num']);
        }
        
        $return_data['category'] = $category;
        $return_data['series'] = array( 
                array('name'=>'3分以下','type'=>'bar','data'=>$level_one),
                array('name'=>'3-4分','type'=>'bar','data'=>$level_two),
                array('name'=>'4-5分','type'=>'bar','data'=>$level_three)
        );
        return $return_data;
    }
    //酒店各阶段占比数据-echart数据格式化
    private function _format_echart_data_with_persenthotel($data){
        if(empty($data)) return null;
        $return_data = array();
        foreach ($data as $key=>$val){
            if($key!='count'){
                $return_data[] = array('name'=>$key,'value'=>$val*100);    
            }
        }

        return $return_data;
    }
    //酒店热力图-echart数据格式化
    private function _format_echart_data_with_hothotel($data){
        if(empty($data)) return null;
        $return_data = array();
        foreach ($data as $key=>$val){
            //经度，纬度，价格，酒店名称，城市名称，评分，图片地址
            $value_array = array($val['longitude'],$val['latitude'],$val['price'],$val['name'],$val['city_name'],$val['rank'],$val['img_url']);
            array_push($return_data, array('name'=>$val['name'],'value'=> $value_array) );
        }
        return $return_data;
    }

    //链接pgsql(dataex爬虫数据)
    protected function conncetPgsql(){
        $conn_string  =  "host=".C(DATAEXGP_HOST)." port=".C(DATAEXGP_PORT)." dbname=".C(DATAEXGP_DB_NAME)." user=".C(DATAEXGP_DB_USER)." password=".C(DATAEXGP_DB_PWD); 
        $dbconn = pg_connect($conn_string);
        
        if ($dbconn){
            return $dbconn;
        } else {
            pg_close($dbconn);
            $this->error('链接pg库失败');
        }
    }

    //酒店地图-全国及前五名，各星级数据量-sql
    public function getTopHotelSql(){
        $sql = 'SELECT COALESCE (city_name, \'全国酒店数量\') as "city",count(*) as "total_num",';
            $sql .=' COUNT (CASE WHEN rank < 3 THEN 1 END) as "one_num", ';
            $sql .=' COUNT (
                CASE 
                WHEN  rank BETWEEN 3
                AND 4 THEN
                    1
                END
            ) as "two_num",';
            $sql .='COUNT (
                CASE 
                WHEN  rank BETWEEN 4
                AND 5 THEN
                    1
                END
            ) as "three_num" ';
            $sql .=' from elong_domestic_hotel ';
            $sql .=' GROUP BY ROLLUP(city_name) ';
            $sql .=' ORDER BY 2 desc limit 6';
        return $sql;
    }

    //酒店价格占比-sql
    public function getPriceHotelSql(){
        $price_sql = 'SELECT round( ( COUNT (CASE WHEN price < 100 THEN 1 END)::numeric / COUNT (*) ),3) AS "100以下",';
        $price_sql .='round( ( COUNT (CASE WHEN price > 500 THEN 1 END)::numeric / COUNT (*) ),3) AS "500以上",';
        $price_sql .='round(( COUNT (
            CASE
            WHEN price BETWEEN 100
            AND 200 THEN
                1
            END
        )::numeric / COUNT (*) ),3) AS "100-200",';
        $price_sql .='round(( COUNT (
            CASE
            WHEN price BETWEEN 200
            AND 300 THEN
                1
            END
        )::numeric / COUNT (*) ),3) AS "200-300",';
        $price_sql .='round(( COUNT (
            CASE
            WHEN price BETWEEN 300
            AND 400 THEN
                1
            END
        )::numeric / COUNT (*) ),3) AS "300-400",';
        $price_sql .='count(*)';
        $price_sql .='FROM elong_domestic_hotel';

        return $price_sql;
    }

    public function phprpc_test(){       
        Vendor('phpRPC.phprpc_client');        
        $client = new \PHPRPC_Client('http://www.dataex.com/test');        
        // 或者采用        
        //$client = new \PHPRPC_Client();        
        //$client->useService('http://serverName/index.php/Home/Server');        
        $result = $client->test1();
        echo $result;die;
    }

}
